from logging import RootLogger
from PyQt5.Qt import QThread
from PyQt5.Qt import *
import json
import time
import robot_


class Server_Tcp(QThread):

    def __init__(self,signal):
        super().__init__()
  
        self.signal = signal
        self.robot=None

        #### 初始化，可根据不同的赋值，做出相应的机器人动作
        self.robot_action = 0

        try:
            self.robot = robot_.Robot_Driver()
        except Exception as e:
            self.signal.emit(json.dumps({"source":35,"reason":f"{e}"}))

    #### 状态监测
    def run (self):
        while True:  
            try:
                time.sleep(0.01)
                robot_action_ = self.robot_action
                if robot_action_ == 0:
                    # self.signal.emit(json.dumps({"source":21,}))          
                    self.update_Sys_status()
                    pass
     
                elif robot_action_ == 1:
                    #### Home
                    self.signal.emit(json.dumps({"source":4,}))
                    self.robot.robot_Home()
                    robot_action_ = 0
                    self.update_Sys_status()  
                    return 1
 
            except Exception as e:
                print(e)
    
    ### 系统状态更新
    def update_Sys_status(self,):
        status1 = self.robot.get_Robot_Status()
        
        log = 0
        if status1 == "Alarm":

            try:
            # 设备离线
                if log ==1:
                    self.signal.emit(json.dumps({"source":1,}))

            except Exception as e:
                print(e)
                return None        
        
        elif status1 == "Idle":
            # 正常
            try :
                if log ==1:
                    self.signal.emit(json.dumps({"source":2,}))

            except Exception as e:
                print(e)
                return None

        elif status1 == "Busy" :
            #工作中
            try :
                # 锁定
                if log ==1:
                    self.signal.emit(json.dumps({"source":3,}))
            
            except Exception as e:
                print(e)
                return None
        

        elif status1 == "Home":
            #回零中 
            try :
                if log ==1:
                    self.signal.emit(json.dumps({"source":4,}))
                
            except Exception as e:
                print(e)
                return None

    def status_robot (self,status,s):
        
        if status ==0:
            # 打印设备离线
            pass

        elif status ==1:
            # 设备正常
            return 1

        elif status == 2 or status == 5:
            #锁定状态
            try :
                # self.robot.set_Reset_mode(8, slave=s)
                time.sleep(0.01)
            except Exception as e:
                print(e)
                return None

        elif status == 3 or status == 4 or status == 6:
            # 正在运行
            pass
       
        return 0
